//
//  FileController.swift
//  swifttest1
//
//  Created by kologe on 2024/10/7.
//  description:文件操作

import Foundation
class FileController{
    static var shared:FileController = FileController() //实现较多数据写入时用的
 
    
    public static func writeToFile(fileUrl:URL,data:Data){
        do{
            // 使用fileUrl.path 不能使用fileUrl.path()因为 fileurl.path没有file://前缀 ， 如果有就会一直判断文件不存在
            if FileManager.default.fileExists(atPath: fileUrl.path) {
                let fileHandle = try FileHandle(forWritingTo: fileUrl)
                fileHandle.seekToEndOfFile()
                fileHandle.write(data)
                fileHandle.closeFile()
            } else {
                try data.write(to: fileUrl)
            }
            //            print("Data successfully written to file: \(fileUrl.path)")
        }catch{
            error_log("Failed to write data to file: \(error.localizedDescription)")
        }
    }
    
    
    
    public static func writeToFile(filePath:String,data:Data){
        do{
            let fileUrl = URL(fileURLWithPath: filePath)
            // 使用fileUrl.path 不能使用fileUrl.path()因为 fileurl.path没有file://前缀 ， 如果有就会一直判断文件不存在
            if FileManager.default.fileExists(atPath: fileUrl.path) {
                let fileHandle = try FileHandle(forWritingTo: fileUrl)
                fileHandle.seekToEndOfFile()
                fileHandle.write(data)
                fileHandle.closeFile()
            } else {
                try data.write(to: fileUrl)
            }
            //            print("Data successfully written to file: \(fileUrl.path)")
        }catch{
            error_log("Failed to write data to file: \(error.localizedDescription)")
        }
    }
    
    public static func readFromFile(fileUrl:URL) -> Data?{
        do{
            if FileManager.default.fileExists(atPath: fileUrl.path){
                let fileHandle = try FileHandle(forReadingFrom: fileUrl)
                let fileData = try fileHandle.readToEnd()
                try fileHandle.close()
                return fileData
            }
        }catch{
            error_log("Failed to read data from file \(fileUrl.path): \(error.localizedDescription)")
        }
        return nil
    }
    
    public static func overwriteToFile(fileUrl:URL,data:Data){
        do{
            try data.write(to: fileUrl)
            //            print("Data successfully written to file: \(fileUrl.path)")
            info_log("overwriteToFile : \(fileUrl)")
        }catch{
            error_log("Failed to overwirte data to file: \(error.localizedDescription)")
        }
    }
    
    
    //防止文件名冲突
    public static func getFilePath(fileName:String,dirPath:String) -> String{
        let nfileName = fileName
        var filePath = dirPath.appending(nfileName)
        
        var count = 1
        //!!! 这里判断的是没有file:// 的字符串。
        while( FileManager.default.fileExists(atPath: URL(string:filePath)!.path)){
            if let dotIndex = fileName.lastIndex(of: "."){
                let baseName = fileName[..<dotIndex]
                let extensionName = fileName[dotIndex...]
                let tempfileName = baseName + "\(count)" + extensionName
                filePath = dirPath.appending(tempfileName)
            }else{
                let tempfileName = nfileName+"\(count)"
                filePath = dirPath.appending(tempfileName)
            }
            count+=1
        }
        return filePath
    }
    
    public static func fileSize(filepath:String)-> UInt64?{
        let fileManager = FileManager.default
        
        do {
            let attributes = try fileManager.attributesOfItem(atPath: filepath)
            if let fileSize = attributes[.size] as? UInt64 {
                return fileSize
            }
        } catch {
            error_log("Error getting file size: \(error.localizedDescription)")
        }
        
        return nil
    }
    
    public static func fileSize(fileUrl:URL) -> UInt64?{
        let fileManager = FileManager.default
        
        do {
            let attributes = try fileManager.attributesOfItem(atPath: fileUrl.path)
            if let fileSize = attributes[.size] as? UInt64 {
                return fileSize
            }
        } catch {
            error_log("Error getting file size: \(error.localizedDescription)")
        }
        
        return nil
    }
    
    public static func createDownloadFileName(userName:String,fileName:String) -> String{
        if let downloadsURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first{
            let downloadName = downloadsURL.path.appending(userName+"*"+fileName)
            return downloadName
        }else{
            error_log("error DownloadFilePath \(userName)*\(fileName) create failed")
            return ""
        }
    }
    public static func createTempFile(DirName:String,fileName:String) -> String{
        let tempPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first
        let tempURL = tempPath?.path
        let logDir = tempURL!.appending(DirName)
        
        //生成文件夹
        createDir(dirPath: logDir)
        let logFile = logDir.appending("/"+fileName)
        if FileManager.default.fileExists(atPath: logFile){
            return logFile
        }
        if FileManager.default.createFile(atPath: logFile, contents: nil){
            return logFile
        }else{
            error_log("error createTempFile \(DirName)/\(fileName) failed")
            return ""
        }
    }
    
    public static func createLogFile(DirName:String,fileName:String) -> String{
        let cachePath = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
        let cacheURL = cachePath?.path
        let logDir = cacheURL!.appending("/Logs/" + DirName + "/")
        
        //生成文件夹
        createDir(dirPath: logDir)
        let logFile = logDir.appending(fileName)
        if FileManager.default.createFile(atPath: logFile, contents: nil){
            return logFile
        }else{
            error_log("error CreateLogFile \(DirName)/\(fileName) failed")
            return ""
        }
    }
    public static func createDir(dirPath:String){
        do{
            if !FileManager.default.fileExists(atPath: dirPath){
                try FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true)
            }
        }catch{
            error_log("error createDir failed ,error is  \(error.localizedDescription)")
        }
    }
    
    public static func deleteFile(filePath:String){
        do{
            let url = URL(fileURLWithPath: filePath)
            if FileManager.default.fileExists(atPath: filePath){
                try FileManager.default.removeItem(at: url)
                info_log("deleteFile delete \(filePath) success")
            }
        }catch{
            error_log("error deleteFile: ,error is \(error.localizedDescription)")
        }
    }
    
}
